/*
 * @Author: ChunLai
 * @Date: 2022-06-07 09:25:50
 * @LastEditTime: 2025-11-20 14:19:40
 * @Description: 微信JSDK获取用户信息
 * @FilePath: \01.latest-short-insure\src\utils\wxJsSdk.js
 */
import $http from "@/utils/request";
import store from "../store";
import { Toast } from "vant";
import { addUrlPara } from "@/utils/index.js";

const publicAppId = "wx7f77b13feef420d9";

//公众号获取code
export const getLogin = (workNum, pid, sid, envDomain) => {
  let demoUrl = `/app_h5/latestshort/index.html#/planbook?workNum=${workNum}&isShare=1&id=${pid}&sid=${sid}&timeStamp=${new Date().valueOf()}&env=${envDomain}`; // window.location.href
  let urlNow = encodeURIComponent(demoUrl);
  let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${publicAppId}&redirect_uri=${urlNow}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
  // console.log(demoUrl)
  window.location.replace(url);
};

/**
 * 获取url中的参数
 */
export const getUrlData = () => {
  var strs;
  var url = window.location.href; //获取url中"?"符后的字串
  var theRequest = new Object();
  if (url.indexOf("?") != -1) {
    url = url.substr(url.indexOf("?"));
    var str = url.substr(1);
    strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      var index = strs[i].indexOf("=");
      theRequest[strs[i].slice(0, index)] = unescape(
        strs[i].slice(index + 1, strs[i].length)
      );
    }
  }
  return theRequest;
};

/** 关闭微信浏览器 */
export const closeWXWindow = () => {
  // 微信浏览器里有一个 WeixinJSBridge 对象，就像普通浏览器里必有 window 对象一样，无需额外引入
  // 不过保险起见，还是判断一下是否为空
  if (WeixinJSBridge?.invoke) {
    WeixinJSBridge.invoke("closeWindow", {}, () => {
      console.error("关闭微信网页失败");
    });
  }
};
export const isWxChat = () => {
  // console.log('isWxChat----');
  let res = false;
  let ua = window.navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    res = true;
  }
  return res;
};
export const wechatInitShareConfig = (
  shareUrl,
  ttValue = "",
  descValue = ""
) => {
  // console.log('wechatInitShareConfig----');
  if (!isWxChat()) {
    return;
  }
  $http
    .post("/wechart/getWxconfig", {
      url: `${window.location.pathname}${window.location.search}`,
    })
    .then(
      (res) => {
        if (res.result == 1) {
          let config = res.data;
          jWeixin.config({
            debug: false,
            appId: config.appId,
            timestamp: config.timestamp,
            nonceStr: config.nonceStr,
            signature: config.signature,
            jsApiList: [
              "onMenuShareAppMessage",
              "showMenuItems",
              "hideOptionMenu",
            ],
          });
          // 分享Api操作
          let baseConfig = store.state.home || {},
            shareMsg = baseConfig.shareInfo || {},
            iconUrl = `${shareMsg.icon || ""}`,
            shareTt = `${shareMsg.title || ""}`,
            shareDesc = `${shareMsg.desc || ""}`;
          Toast({
            message: `已复制链接,点击右上方分享`,
          });
          jWeixin.ready(function () {
            if (iconUrl && iconUrl.indexOf("http") === -1) {
              iconUrl = `/${shareMsg.icon || ""}`;
            }
            // 老版本分享Api
            jWeixin.onMenuShareAppMessage({
              title: `${ttValue || shareTt}`,
              desc: `${descValue || shareDesc}`,
              link: `${addUrlPara("sharepage", "1", shareUrl)}`,
              imgUrl: `${iconUrl}`,
              success: function (res) {
                // 用户点击了分享后执行的回调函数
                console.log("onMenuShareAppMessage", res);
                // Toast({
                //   message: `分享成功,请联系客户尽快完成操作`,
                // });
              },
              cancel: function () {},
              fail: function () {},
            });
          });
        }
      },
      (err) => {}
    );
};
